package com.bankapp.domain.bank;


import com.bankapp.service.bank.EmailService;
import java.io.Closeable;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Bank implements Serializable, Closeable {
    private List<Client> clients;
    private List<ClientRegistrationListener> listeners;

    public Bank() {
        this(null);
    }

    public Bank(final List<ClientRegistrationListener> listeners) {
        clients = new ArrayList<Client>();
        this.listeners = listeners;

        if (this.listeners == null) {
            this.listeners = new ArrayList<ClientRegistrationListener>();
            this.listeners.add(new PrintClientListener());
            EmailService emailService = new EmailService();
            emailService.start();
            this.listeners.add(new EmailNotificationListener(emailService));
        }
    }

    public Client[] getClientsArray() {
        return clients.toArray(new Client[clients.size()]);
    }

    public void addClient(final Client client) {
        clients.add(client);
        for (ClientRegistrationListener listener : listeners) {
            listener.onClientAdded(client);
        }
    }

    @Override
    public void close() throws IOException {
        for (Closeable listener : listeners) {
            listener.close();
        }
    }

    class PrintClientListener implements ClientRegistrationListener, Serializable {
        @Override
        public void onClientAdded(final Client client) {
            System.out.println("Client added: " + client.toString());
        }

        @Override
        public void close() throws IOException {
        }
    }

    class EmailNotificationListener implements ClientRegistrationListener, Serializable {
        private EmailService emailService;

        public EmailNotificationListener(EmailService emailService) {
            this.emailService = emailService;
        }

        @Override
        public void onClientAdded(final Client client) {
            Email email = client.getEmail();
            emailService.sendNotificationEmail(email);
            System.out.println("Notification email for client " + client.getName() + " to be sent");
        }

        @Override
        public void close() throws IOException {
            emailService.close();
        }
    }
}
